package cn.zhaozhiqi.producer;

import cn.zhaozhiqi.constants.Constants;
import cn.zhaozhiqi.pojo.domain.Order;
import cn.zhaozhiqi.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

/**
 * MQ监听器
 */
@Slf4j
@RocketMQTransactionListener(txProducerGroup = Constants.Mq.TX_ORDER_PAY_GROUP)
public class CreateOrderPayListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IOrderService orderService;
    /**
     * 执行本地事务  msg: 消息对象   arg : 扩展参数
     * @param message
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        //扩展参数即是我们传入的Order对象,拿到需保存
        try {
            Order order = (Order) arg;
            orderService.updateById(order);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }

    /**
     * 回查本地事务
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        return null;
    }
}
